#! /usr/bin/env python

import Image
import ImageDraw
import ImageFilter


def blur_circle(base_image, x, y, r):
    """

    Blurs a cirle radius r on the image provided, given the x & y coordinates

    """
    circle_mask = Image.new("RGBA", (2*r + 1, 2*r + 1), (0, 0, 0, 0))
    draw = ImageDraw.Draw(circle_mask)
    draw.ellipse((0, 0, 2 * r, 2 * r), fill=(255, 255, 255, 255))
    del draw

    box = (x-r-1, y-r-1, x+r, y+r)
    non_blurred_box = base_image.crop(box)
    blurred_box = non_blurred_box.copy()
    for i in range(10):
        blurred_box = blurred_box.filter(ImageFilter.BLUR)
    composite_box = Image.composite(blurred_box, non_blurred_box, circle_mask)
    base_image.paste(composite_box, box)


def blur_image(file_in, file_out, humans, r):
    """

    blur_image blurs faces in an image and saves the image in the filename
    given (file_out).  The faces are blurred with circles, radius r, and the
    coordinates are from the array of human variables passed in. These are
    assumed to be a dictionary. The faces are only blurred if the human is
    a student and they are not currently signed up to the website (UserId == 0).

    """

    im = Image.open(file_in)
    for human in humans:
        if human["IsStudent"] and human["UserId"] == 0:
            blur_circle(im, human["X"], human["Y"], r)
    im.save(file_out, "JPEG", quality=95)
    return ""


def blur_image_wrapper(params):
    """ Wraps the blur_image function so that it can be used for jsonrpc."""
    return blur_image(
        params["FileIn"],
        params["FileOut"],
        params["Humans"],
        params["Radius"])
